import React, { useState } from 'react';
import { MailOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { Link } from 'react-router-dom';
type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group'
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}
const menus = [
  {
    to: 'home',
    key: '1',
    name: 'home',
    icon: <MailOutlined />,
  },
  {
    to: 'firstLevelOne',
    key: '2',
    name: '一级菜单1',
    icon: <MailOutlined />,
  },
  {
    to: '',
    key: '3-0',
    name: '一级菜单2',
    icon: <MailOutlined />,
    children: [
      {
        to: 'firstLeveltwo',
        key: '3',
        name: '二级级菜单1',
        icon: <MailOutlined />,
      },
      {
        to: 'firstLevelTwosecondLeveltwo',
        key: '4',
        name: '二级级菜单2',
        icon: <MailOutlined />,
        // children: [
        //   {
        //     to: '/firstLeveltwo/one',
        //     key: '5',
        //     name: 'firstLeveltwo/one',
        //     icon: <MailOutlined />,
        //   },
        //   {
        //     to: '/firstLeveltwo/two',
        //     key: '6',
        //     name: 'firstLeveltwo/two',
        //     icon: <MailOutlined />,
        //   },
        // ],
      },
    ],
  },
];

const recursiveMenu = (menus: any): any => {
  let selectedKey = '';
  let openKey = '';
  const menusNode = menus?.map((item: any, index: number) => {
    if (item.to === window.location.pathname) {
      selectedKey = item.key;
      openKey = item.key;
    }
    if (!item.to && item.children) {
      return getItem(
        item.name,
        item.key,
        item.icon,
        item.children.map((subitem: any, index: number) => {
          if (subitem.to === window.location.pathname) {
            selectedKey = subitem.key;
            openKey = item.key; // 取上一层的key
          }
          return getItem(
            <Link to={subitem.to}>{subitem.name} </Link>,
            subitem.key,
            subitem.icon ? subitem.icon : null,
            subitem.children ? recursiveMenu(subitem.children) : undefined
          );
        })
      );
    } else {
      return getItem(
        <Link to={item.to}>{item.name} </Link>,
        item.key,
        item.icon ? item.icon : null
      );
    }
  });
  return { menusNode, selectedKey, openKey };
};

const recursiveMenuTmp = recursiveMenu(menus);

const items: MenuItem[] = recursiveMenuTmp.menusNode;

const MenuLayout: React.FC = () => {
  const [defaultKey] = useState(recursiveMenuTmp.selectedKey);
  const [defaultOpenKey] = useState(recursiveMenuTmp.openKey);
  return (
    <Menu
      defaultSelectedKeys={[defaultKey]}
      defaultOpenKeys={[defaultOpenKey]}
      mode="inline"
      theme="dark"
      items={items}
    />
  );
};

export default MenuLayout;
